import React, {Component} from 'react';
import {connect} from 'react-redux';
import {messages} from "share/common";
import {Button, Spin, Form, Checkbox, message, Input} from 'antd'
import 'styles/supplier-management/new-consumer-management/edit-frams/edit-frame.scss'
import Priority from 'components/template/priority';
import NewConsumerServer from '../new-consumer-server';
import InputLanguage from 'components/template/input-language'

const FormItem = Form.Item;
const Group = Checkbox.Group;

@Form.create()
class OtherRule extends Component {

  constructor(props) {
    super(props);
    this.supplier = [
      {
        name: messages('supplier-1.key80')/*机票*/,
        key: 'withOtherFlightSupplier',
        inputKey: 'otherFlightSupplierName',
        inputKeyEn: 'otherFlightSupplierEnName'
      },{
        name: messages('supplier-1.key82')/*火车*/,
        key: 'withOtherTrainSupplier',
        inputKey: 'otherTrainSupplierName',
        inputKeyEn: 'otherTrainSupplierEnName'
      },{
        name: messages('supplier-1.key81')/*酒店*/,
        key: 'withOtherHotelSupplier',
        inputKey: 'otherHotelSupplierName',
        inputKeyEn: 'otherHotelSupplierEnName'
      }
    ];
    this.state = {
      loading: false,
      priorityData: {},
      priDefalultValue: {}, // 默认值
      isNew: true,// 是否是新建
    };
  }

  componentWillMount() {
    const {params, tenant} = this.props;
    const initValue = {
      levelCode: params.levelCode || "TENANT",
      levelOrgId: params.levelOrgId || tenant.id,
      levelOrgName: params.levelOrgName || tenant.tenantName,
    }
    if(params.companyInfos){
      initValue.distribution = {
        companies: params.companyInfos ? params.companyInfos : []
      }
    }
    this.setState({
      priorityData: params,
      isNew: params.levelCode ? false : true,
      priDefalultValue: initValue
    }, this.props.form.resetFields);
  }

  onCancelEdit = () => {
    this.props.close();
  };

  onSaveData = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values = this.formatParams(values)
        const {priDefalultValue, isNew, priorityData} = this.state;
        if (!priDefalultValue) {
          message.error(messages('supplier-1.key185')/*请填写所属组织*/);
          return;
        }else if(priDefalultValue.distribution){
          if(priDefalultValue.distribution.companies.length <= 0){
            message.error(messages('supplier-1.key187')/*请填写公司*/);
            return;
          }
        }
        const pri = {
          ...priDefalultValue,
          companies: priDefalultValue.distribution ? priDefalultValue.distribution.companies.map(item => item.id) : [],
        }
        delete pri.distribution;
        let params = Object.assign({tenantId: this.props.tenant.id,}, pri, values);
        if (!isNew) {
          params = Object.assign({}, priorityData, params);
        }
        NewConsumerServer(this).saveOtherPriData(params).then(res => {
          this.props.close('saved');
        })
      }
    })
  }

  formatParams = (values) => {
    const params = Object.assign({}, values)
    this.supplier.forEach((supplier) => {
      if (values[supplier.key]) {
        try {
          if (!values[supplier.inputKey].i18n) {
            values[supplier.inputKey].i18n = []
          }
          params[supplier.inputKeyEn] = values[supplier.inputKey].i18n.find(item => item.language === 'en').value || ''
          params[supplier.inputKey] = values[supplier.inputKey].name
        } catch (error) {
          params[supplier.inputKey] = ''
          params[supplier.inputKeyEn] = ''
        }
      }
    })
    return params
  }

  getInitialValue = (key, keyEn) => {
    const { priorityData = {} } = this.state
    return {
      name: priorityData[key] || '',
      i18n: [
        {
          language: 'zh_cn',
          value: priorityData[key] || '',
        },
        {
          language: 'en',
          value: priorityData[keyEn] || '',
        }
      ]
    }
  }

  onPriorityChange = (value) => {
    this.setState({
      priDefalultValue: value,
    })
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    const {priDefalultValue, isNew, loading} = this.state;
    const formLayout = {
      labelCol: {span: 6, offset: 1},
      wrapperCol: {span: 14}
    }
    return (
      <div className='edit-frame'>
        <Spin spinning={loading}>
          <Form className="new-form">
            <div className='other-edit-lable'>
              <Priority
                top='TENANT'
                formItemLayout={formLayout}
                disabledTop={!isNew}
                companyProps={{disabled: !isNew}}
                defaultValue={priDefalultValue}
                onChange={this.onPriorityChange}
              />
            </div>
            <h3 style={{borderBottom: 0}}>
              <div className='other-rule-edit-title'>
                {messages('supplier-1.key230')/*差旅申请单启用【其他供应商】行程类型*/}
              </div>
            </h3>
            <div className='other-edit-lable'>
              {this.createRule(formLayout, getFieldDecorator)}
            </div>
          </Form>
        </Spin>
        <br/><br/><br/><br/>
        <div className='affix-bottom'>
          <Button loading={loading} onClick={this.onSaveData} type='primary'>
            {messages('common.save')/*保存*/}
          </Button>
          &nbsp;
          <Button onClick={this.onCancelEdit}>
            {messages('common.cancel')/*取消*/}
          </Button>
        </div>
      </div>
    )
  }

  createRule = (formLayout, getFieldDecorator) => {
    const {priorityData} = this.state;
    const { getFieldValue } = this.props.form;
    return this.supplier.map(item => {
      return (
        <div className="inline-form-item">
          <FormItem {...formLayout} label={`${item.name}${messages('supplier-1.key227')/*行程\"其他\"供应商*/}`}>
          {
            getFieldDecorator(item.key, {
              initialValue: priorityData[item.key] || false,
              valuePropName: 'checked'
            })(
              <Checkbox value={item.key}>{messages('supplier-1.key35')/*启用temp*/}</Checkbox>
            )
            }
          </FormItem>
          {
            getFieldValue(item.key) ? <FormItem {...formLayout}>
              {
                getFieldDecorator(item.inputKey, {
                  initialValue: this.getInitialValue(item.inputKey, item.inputKeyEn)
                })(
                  <InputLanguage
                    placeholder={messages('supplier-1.key538')/*请输入自定义\"其他\"消费商名称*/}
                    type="text"
                    maxLength={15}
                  />
                )
              }
            </FormItem> : ''
          }
        </div>
      )
    })
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  }
}

export default connect(mapStateToProps)(OtherRule);


